<template>
	<div class="menu-container">
	  <!-- 顶部导航栏 -->
	  <van-nav-bar
		title="点菜"
		fixed
		placeholder
	  />
  
	  <div class="menu-content">
		<!-- 左侧分类导航 -->
		<div class="type-nav">
		  <div 
			v-for="type in recipeTypes" 
			:key="type.id"
			:class="['type-item', { active: selectedType === type.id }]"
			@click="handleTypeChange(type.id)"
		  >
			{{ type.name }}
		  </div>
		</div>
  
		<!-- 右侧菜品列表 -->
		<div class="content-container">
		  <div class="recipe-list">
			<template v-if="recipes.length > 0">
			  <div v-for="recipe in recipes" :key="recipe.id" class="recipe-item">
				<div class="recipe-info">
				  <div class="recipe-name">{{ recipe.name }}</div>
				  <div class="recipe-price">¥{{ recipe.price || 0 }}</div>
				</div>
				<div class="recipe-action">
				  <template v-if="cartItems.find(item => item.id === recipe.id)">
					<van-stepper
					  v-model="cartItems.find(item => item.id === recipe.id).quantity"
					  theme="round"
					  button-size="22"
					  disable-input
					  @plus="increaseQuantity(recipe.id)"
					  @minus="decreaseQuantity(recipe.id)"
					/>
				  </template>
				  <van-button 
					v-else 
					type="primary" 
					size="small" 
					round 
					icon="plus"
					@click="addToCart(recipe)"
				  />
				</div>
			  </div>
			</template>
			<van-empty v-else description="暂无菜品" />
		  </div>
		</div>
	  </div>
  
	  <!-- 底部购物车 -->
	  <div class="cart-bar" v-if="cartItems.length > 0">
		<div class="cart-info" @click="showCartDetail = true">
		  <van-badge :content="getTotalQuantity()" :show-zero="false">
			<van-icon name="shopping-cart-o" size="24" />
		  </van-badge>
		  <div class="cart-price">
			<div class="total-price">¥{{ getTotalPrice() }}</div>
		  </div>
		</div>
		<van-button 
		  type="primary" 
		  size="small" 
		  round
		  :disabled="cartItems.length === 0"
		>
		  去结算
		</van-button>
	  </div>
  
	  <!-- 购物车详情弹窗 -->
	  <van-popup
		v-model:show="showCartDetail"
		position="bottom"
		round
		:style="{ height: '40%' }"
	  >
		<div class="cart-detail">
		  <div class="cart-detail-header">
			<h3>已选商品</h3>
			<van-button 
			  type="default" 
			  size="small" 
			  plain
			  @click="clearCart"
			>
			  清空购物车
			</van-button>
		  </div>
		  <van-cell-group inset>
			<van-cell 
			  v-for="item in cartItems" 
			  :key="item.id"
			  :title="item.name"
			  :label="'¥' + (item.price || 0) * item.quantity"
			>
			  <template #right-icon>
				<van-stepper
				  v-model="item.quantity"
				  theme="round"
				  button-size="22"
				  disable-input
				  @plus="increaseQuantity(item.id)"
				  @minus="decreaseQuantity(item.id)"
				/>
			  </template>
			</van-cell>
		  </van-cell-group>
		</div>
	  </van-popup>
	</div>
  </template>
  
<script setup>
// 引入Vue 3的响应式引用（ref）和生命周期钩子（onMounted）
import { ref, onMounted } from 'vue'
import { getRecipes, getRecipesByType } from '../../api/recipe'
import { getRecipeTypes } from '../../api/recipeType'
import { useCart } from '../../store/cart'
console.log('pages-index');

const recipeTypes = ref([])
const recipes = ref([])
const selectedType = ref(null)
const { cartItems, addToCart, removeFromCart, updateQuantity, getTotalPrice, getTotalQuantity, clearCart } = useCart()
const showCartDetail = ref(false)

// 获取所有食谱种类
async function fetchRecipeTypes() {
  try {
    recipeTypes.value = await getRecipeTypes()
    if (recipeTypes.value.length > 0) {
      selectedType.value = recipeTypes.value[0].id
      await fetchRecipesByType(selectedType.value)
    }
  } catch (error) {
    console.error('获取食谱种类失败:', error)
  }
}

// 根据类型获取食谱
async function fetchRecipesByType(typeId) {
  try {
    recipes.value = await getRecipesByType(typeId)
  } catch (error) {
    console.error('获取食谱失败:', error)
  }
}

// 切换食谱类型
async function handleTypeChange(typeId) {
  selectedType.value = typeId
  await fetchRecipesByType(typeId)
}

// 增加菜品数量
const increaseQuantity = (recipeId) => {
  const item = cartItems.value.find(item => item.id === recipeId)
  if (item) {
    updateQuantity(recipeId, item.quantity + 1)
  }
}

// 减少菜品数量
const decreaseQuantity = (recipeId) => {
  const item = cartItems.value.find(item => item.id === recipeId)
  if (item && item.quantity > 1) {
    updateQuantity(recipeId, item.quantity - 1)
  } else {
    removeFromCart(recipeId)
  }
}

// 在组件被挂载后（mounted）执行getBooks函数，获取并更新书籍数据
onMounted(() => {
  fetchRecipeTypes()
})
</script>

<style scoped>
.menu-container {
  height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.menu-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  margin-top: 46px;
}

.type-nav {
  width: 85px;
  background: #f7f8fa;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.type-nav::-webkit-scrollbar {
  display: none;
}

.type-item {
  padding: 15px 10px;
  text-align: center;
  font-size: 14px;
  color: #323233;
  border-left: 2px solid transparent;
  position: relative;
}

.type-item.active {
  background: #fff;
  color: #1989fa;
  border-left-color: #1989fa;
}

.content-container {
  flex: 1;
  background: #fff;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.recipe-list {
  padding: 10px;
}

.recipe-item {
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recipe-name {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 15px;
}

.recipe-price {
  color: #ee0a24;
  font-weight: bold;
  font-size: 14px;
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  z-index: 100;
}

.cart-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-price {
  font-size: 16px;
}

.total-price {
  font-weight: bold;
  color: #ee0a24;
}

.cart-detail {
  padding: 16px;
}

.cart-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.cart-detail-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}
</style>